import mongoose, { Document, Schema } from 'mongoose';

export interface ICarDocument extends Document {
  userId: string;
  name: string;
  category: string;
  brand: string;
  carModel: string;
  productionTime: number;
  purchaseTime: number;
  licensePlate?: string;
  notes?: string;
  // 车类型
  vehicleType: string;
  // 燃油车特有字段
  currentMileage?: number;
  fuelCapacity?: number;
  fuelType?: string;
  purchasePrice?: number;
  currency?: string;
  // 电车特有字段
  batteryCapacity?: number;
  mileage?: number;
  createdAt: Date;
  updatedAt: Date;
}

const carSchema = new Schema<ICarDocument>(
  {
    userId: {
      type: String,
      required: [true, '用户ID是必需的'],
    },
    name: {
      type: String,
      required: [true, '车辆昵称是必需的'],
      trim: true,
      maxlength: [50, '车辆昵称不能超过50个字符'],
    },
    category: {
      type: String,
      required: [true, '车辆类型是必需的'],
      // 移除硬编码枚举，支持配置文件中的值
    },
    brand: {
      type: String,
      required: [true, '品牌是必需的'],
      trim: true,
      maxlength: [50, '品牌不能超过50个字符'],
    },
    carModel: {
      type: String,
      required: [true, '型号是必需的'],
      trim: true,
      maxlength: [100, '型号不能超过100个字符'],
    },
    productionTime: {
      type: Number,
      required: [true, '生产时间是必需的'],
    },
    purchaseTime: {
      type: Number,
      required: [true, '购买时间是必需的'],
    },
    licensePlate: {
      type: String,
      trim: true,
      maxlength: [20, '车牌号不能超过20个字符'],
    },
    notes: {
      type: String,
      trim: true,
      maxlength: [500, '备注不能超过500个字符'],
    },
    vehicleType: {
      type: String,
      required: [true, '车类型是必需的'],
      // 支持 'fuel', 'electric', 'motor' 等值
    },
    // 燃油车特有字段
    currentMileage: {
      type: Number,
      min: [0, '当前里程不能为负数'],
    },
    fuelCapacity: {
      type: Number,
      min: [0, '油箱容积不能为负数'],
    },
    fuelType: {
      type: String,
      // 支持配置文件中的所有燃油类型
    },
    purchasePrice: {
      type: Number,
      min: [0, '购买价格不能为负数'],
    },
    currency: {
      type: String,
      default: 'CNY',
      // 支持 'CNY', 'USD', 'EUR'
    },
    // 电车特有字段
    batteryCapacity: {
      type: Number,
      min: [0, '电池容量不能为负数'],
    },
    mileage: {
      type: Number,
      min: [0, '续航里程不能为负数'],
    },
  },
  {
    timestamps: true,
  }
);

// 索引
carSchema.index({ userId: 1 });
carSchema.index({ category: 1 });
carSchema.index({ brand: 1 });
carSchema.index({ purchaseTime: 1 });

// 虚拟字段：车辆年龄（年）
carSchema.virtual('age').get(function (this: ICarDocument) {
  const now = Date.now();
  const purchaseTime = this.purchaseTime;
  return Math.floor((now - purchaseTime) / (1000 * 60 * 60 * 24 * 365));
});

// 确保虚拟字段在JSON序列化时包含
carSchema.set('toJSON', { virtuals: true });

export const Car = mongoose.model<ICarDocument>('Car', carSchema);
